<?php

namespace zhtfrontend\modules\cus\controllers;

use common\components\extenders\RequestManage;
use common\components\helpers\Fun;
use common\models\datas\AccountRecord;
use common\models\datas\Customer;
use common\models\datas\CustomerRecharge;
use common\models\datas\Student;
use dosamigos\qrcode\QrCode;
use linslin\yii2\curl\Curl;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;
use zhtfrontend\components\bases\BaseController;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\modules\cus\components\services\Capital;
use zhtfrontend\modules\cus\components\services\Cus;
use zhtfrontend\modules\cus\components\services\Cusfc;
use zhtfrontend\modules\cus\models\forms\OrdersForm;

class CustomerController extends BaseController
{
    public $curl;
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        $this->curl = new Curl();
    }

    public function actionIndex()
   {
        $where = \Yii::$app->request->get();
       $model = Customer::find()->where(['site_id'=>Fun::getSiteId()]);
       $model->joinWith('grade');
       if (!empty($where['tel'])) {
           $model->andWhere(['mobile' => $where['tel']]);//tel字段改为mobile
       }
       if (!empty($where['name'])) {
           $model->andWhere(['like','{{%customer}}.name' ,$where['name']]);
       }
       if (!empty($where['customer_status'])) {
           $model->andWhere(['grade_id' => $where['customer_status']]);
       }

       $dataProvider = new ActiveDataProvider([
           'query' => $model,
           'pagination' => ['pageSize' => 12,'pageSizeParam'=>false,'pageParam'=>'p'],
           'sort' => [
               'defaultOrder' => [
                   'id' => SORT_DESC,
               ]
           ],

       ]);
       $list = [];
       $grade = Cus::GetGrade();
       foreach ($grade as $k => $v) {
           $list[null] = '请选择';
           $list[$v->id] = $v->name;
       }
       return $this->render('index',['dataProvider'=>$dataProvider,'list'=>$list,]);
   }

   public function actionCreate(){
       $model = new Customer();
       $model->scenario = 'create';
       if (\Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
           \Yii::$app->response->format = Response::FORMAT_JSON;
           return ActiveForm::validate($model);
       }
       if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $data = \Yii::$app->request->post('Customer');
            $extends = \Yii::$app->request->post('extend');
            $result = Cus::InsertCustomer($data,$extends);
            if($result == 1){
                return $this->redirectMessage('添加成功',Fun::url(['cus/customer/index']));
            }
       }
       $gradeList = ArrayHelper::map(Cus::GetGrade(),'id','name');
       $year = (int)date('Y')-25;
       $years[$year] = $year;
       for ($i= 1;$i<=30;$i++){
           $years[$year-$i] = $year - $i;
       }
       $extend = Cus::GetConfig();
//       print_r($years);die;
       return $this->render('create',['model'=>$model,'gradeList'=>$gradeList,'years'=>$years,'extend'=>$extend]);
   }

   public function actionUpdate(){
       $id = \Yii::$app->request->get('id');
       $model = Customer::findOne($id);
       $model->scenario = 'update';
       if (\Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
           \Yii::$app->response->format = Response::FORMAT_JSON;
           return ActiveForm::validate($model);
       }
       if($model->load(\Yii::$app->request->post()) && $model->validate()){
           $data = \Yii::$app->request->post('Customer');
           $extends = \Yii::$app->request->post('extend');
           $result = Cus::UpdateCustomer($data,$id,$extends);
           if($result == 1){
               return $this->redirectMessage('修改成功',Fun::url(['cus/customer/index']));
           }
       }else{
          // print_r($model->getErrors());die;
       }
       $gradeList = ArrayHelper::map(Cus::GetGrade(),'id','name');
       $year = (int)date('Y')-25;
       $years[$year] = $year;
       for ($i= 1;$i<=30;$i++){
           $years[$year-$i] = $year - $i;
       }
       $extend = Cus::GetConfig('customer',$model);
       return $this->render('create',['model'=>$model,'gradeList'=>$gradeList,'years'=>$years,'extend'=>$extend]);
   }
  public function actionDetails(){
         $id = \Yii::$app->request->get('id');
         $model = Cus::GetInfo($id);
         $arr = Cusfc::GetDataList();
         $datas = [];
         foreach ($arr as $val){
             if(!empty($model[$val['code']])){
                 $data['notes'] = $val['notes'];
                 $data['value'] = $model[$val['code']];
                 $datas[] = $data;
             }
         }
         $studentList = Cus::GetStudentList($id); //学生列表
         $ordersList = []; //其他订单列表提供接口
         return $this->render('details',['model'=>$model,'customerExtend'=>$datas,'dataStudent'=>$studentList,'dataOrdersList'=>$ordersList]);
  }

  public function actionRecharge(){
      $this->layout='@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $model = new CustomerRecharge();
        $model = new OrdersForm();
        $model->scenario = 'recharge';

        //需要支付接口
        $paymentList = [
           [
               'code' => 'wxpay',
               'name' => '微信支付'
           ],
            [
                'code'=>'alipay',
                'name'=>'支付宝支付'
            ]
        ];
        $paymodes = ArrayHelper::map($paymentList,'code','name');
      if (\Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
          \Yii::$app->response->format = Response::FORMAT_JSON;
          return ActiveForm::validate($model);
      }
      if($model->load(\Yii::$app->request->post()) && $model->validate()){
          $customer = Customer::findOne($id);
          $modes = \Yii::$app->request->post('pay');
          $url = '';
          $datas = [
              'sn'              => date('YmdHis'),
              'total_amount'   => $model->total,
              'final_amount'   => $model->total,
              'pay_status'     => 1,
              'ship_status'    => 2,
              'pay_time'       => time(),
              'customer_id'    => $id,
              'status'         => 1,
              'remarks'         => $model->remarks,
              'item_num'         => 1,
              'ip'             => (new RequestManage())->getUserIP(),
              'item_amount'  => $model->total,
              'order_source' => 'background',
              'ship_time'    => time(),
              'order_type'   => 'recharge',
              'cash_money'   => $model->total
          ];
          $result = $this->curl->setPostParams($datas)->post($url); //请求接口保存订单
            foreach ($modes as $key=>$val) {
                if (!empty($val)) {
                    $data[] = [
                        'module_id' => $model->id,
                        'code' => $key,
                        'pay_method' => $paymodes[$key],
                        'money' => $val,
                        'type' => 1,
                    ];
                }
            }

              //Capital::insertPayMode($data); //添加充值方式
              $total = $customer->account + (float)$model->total;
              Cus::UpdateCustomer(['account' => $total],$id); //编辑金额
              return $this->redirectMessage('充值成功',Fun::url(['cus/customer/details','id'=>$id]));

      }
      return $this->render('recharge',['model'=>$model,'payList'=>$paymentList]);
  }

  public function actionBinding(){
      $this->layout='@app/views/layouts/iframe.php';
      $customer_id = \Yii::$app->request->get('id');
      $model = new Student();
      $model->scenario = 'create';
      if (\Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
          \Yii::$app->response->format = Response::FORMAT_JSON;
          return ActiveForm::validate($model);
      }
      if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $arr = Cus::getBirthday($model->IDcard);
            $data = \Yii::$app->request->post('Student');
            $data['customer_id'] = $customer_id;
            $data['age'] = $arr['year'];
            $data['birthday'] = $arr['birthday'];
            $data['site_id'] = Fun::getSiteId();
            $extends = \Yii::$app->request->post('extend');
            $id = Cus::InsertStudent($data,$extends);
            if($id){
                return $this->redirectMessage('绑定学员成功！',Fun::url(['cus/customer/details','id'=>$customer_id]));
            }
      }
      $extend = Cus::GetConfig('student');
      return $this->render('binding',['model'=>$model,'extend'=>$extend]);
  }

  public function actionUpdatestudent(){
      $this->layout='@app/views/layouts/iframe.php';
      $student_id = \Yii::$app->request->get('id');
      $model = Student::findOne($student_id);
      $model->scenario = 'update';
      if (\Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
          \Yii::$app->response->format = Response::FORMAT_JSON;
          return ActiveForm::validate($model);
      }
      if($model->load(\Yii::$app->request->post()) && $model->validate()){
          $arr = Cus::getBirthday($model->IDcard);
          $data = \Yii::$app->request->post('Student');
          $data['age'] = $arr['year'];
          $data['birthday'] = $arr['birthday'];
          $extends = \Yii::$app->request->post('extend');
          $result = Cus::UpdateStudent($data,$model->id,$extends);
          if($result){
              return $this->redirectMessage('绑定学员成功！',Fun::url(['cus/customer/details','id'=>$model->customer_id]));
          }
      }
      $extend = Cus::GetConfig('student',$model);
      return $this->render('binding',['model'=>$model,'extend'=>$extend]);
  }

  public function actionStudentdetails(){
      $student_id = \Yii::$app->request->get('id');
      $model = Student::findOne($student_id);

      $couseList = []; //需要订单模块提供订单课程
      return $this->render('studentdetails',['model'=>$model]);
  }

  public function actionCard(){
      $this->layout='@app/views/layouts/iframe.php';
       $student_id = \Yii::$app->request->get('id');
       $model = Student::findOne($student_id);
       $model->scenario = 'card';
      if (\Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
          \Yii::$app->response->format = Response::FORMAT_JSON;
          return ActiveForm::validate($model);
      }
      if($model->load(\Yii::$app->request->post()) && $model->validate()){
          $data = \Yii::$app->request->post('Student');
          $result = Cus::UpdateStudent($data,$model->id);
          if($result){
              return $this->redirectMessage('绑卡成功！',Fun::url(['cus/customer/details','id'=>$model->customer_id]));
          }
      }
      return $this->render('card',['model'=>$model]);
  }

  public function actionAppointment(){
      $student_id = \Yii::$app->request->get('id');
      $Student = Student::findOne($student_id);
      $modelCustomer = Customer::findOne($Student->customer_id);
      $model = new OrdersForm();
      if (\Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
          \Yii::$app->response->format = Response::FORMAT_JSON;
          return ActiveForm::validate($model);
      }
      $url = '';
      if($model->load(\Yii::$app->request->post()) && $model->validate()){
          //订单模块提供生成订单接口
          $post = \Yii::$app->request->post('OrdersForm');
          $datas = [
              'sn'              => date('YmdHis'),
              'total_amount'   => $model->total_amount,
              'final_amount'   => $model->final_amount,
              'pay_status'     => 1,
              'ship_status'    => 2,
              'pay_time'       => time(),
              'customer_id'    => $Student->customer_id,
              'status'          => 1,
              'remarks'         => $model->remarks,
              'item_num'        => 1,
              'ip'             => (new RequestManage())->getUserIP(),
              'item_amount'  => $model->total_amount,
              'order_source' => 'background',
              'ship_time'    => time(),
              'order_type'   => 'appointment',
              'cash_money'   => 0,
              'goods_id'    => $model->goods_id,
              'student_id'  => $student_id
          ];
        //  print_r($datas);die;
          $result = $this->curl->setPostParams($datas)->post($url); //请求接口保存订单
      }
      return $this->render('appointment',['model'=>$model,'modelCustomer'=>$modelCustomer,'student'=>$Student]);
  }
  /*
   *  打印胸牌
   */

  public function actionChestcard(){
      $this->layout='@app/views/layouts/iframe.php';
      $id = \Yii::$app->request->get('id');
      $model = Cus::GetStudentInfo($id);
      if($model->card_number == null){
          throw new NotFoundHttpException(\Yii::t('zhtfrontend', '请先绑卡！'));
      }
      $path = "images/qrcode/";
      if (!file_exists($path)) {
          mkdir($path);
      }
//      $logo = 'images/member-info1-img-card-student.jpg';
//      if (file_exists($logo)) {
//          $QR = imagecreatefromstring(file_get_contents($model->qrcode_url));        //目标图象连接资源。
//          $logo = imagecreatefromstring(file_get_contents($logo));    //源图象连接资源。
//          $QR_width = imagesx($QR);           //二维码图片宽度
//          $QR_height = imagesy($QR);          //二维码图片高度
//          $logo_width = imagesx($logo);       //logo图片宽度
//          $logo_height = imagesy($logo);      //logo图片高度
//          $logo_qr_width = $QR_width / 4;     //组合之后logo的宽度(占二维码的1/5)
//          $scale = $logo_width/$logo_qr_width;    //logo的宽度缩放比(本身宽度/组合后的宽度)
//          $logo_qr_height = $logo_height/$scale;  //组合之后logo的高度
//          $from_width = ($QR_width - $logo_qr_width) / 2;   //组合之后logo左上角所在坐标点
//
//          //重新组合图片并调整大小
//          /*
//           *  imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
//           */
//          imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,$logo_qr_height, $logo_width, $logo_height);
//      }
//
//      //输出图片
//      imagepng($QR, $path.$model->card_number.'.png');
//      imagedestroy($QR);
//      imagedestroy($logo);
      $filesize = @getimagesize($model->qrcode_url);
      if ($model->qrcode_url == null || !$filesize) {
          $pathFile ='images/qrcode/' . $model->card_number . '.png';
          QrCode::png($model->card_number, $pathFile, 'H', 6, 2);
          $model->qrcode_url = $pathFile;
          $model->save(false);
      }
      return $this->render('chestcard',['model'=>$model]);
  }

  public function actionCourse(){
      $this->layout='@app/views/layouts/iframe.php';
      $get = \Yii::$app->request->get();
      $where = [];
      //商品模块接口输出
      $model = Goods::find();
      $pages = new Pagination(['route'=>'cus/customer/course','totalCount' => $model->count(), 'pageSize' => 12,'params'=>$where]);
      isset($get['page']) ? $pages->page = $get['page'] - 1 : 0;

      $data = $model->offset($pages->offset)->limit($pages->limit)->all();
      $datas = Fun::asArray($data, ['teacherStr', 'mechanic_name','room_name','class_time','class_count','type_name']);
//      $data = [];
//      $url = '';
//      $result = $this->curl->setPostParams($data)->post($url); //请求接口返回商品列表

      return $this->render('course',['data'=>$datas,'pages'=>$pages]);

  }

  public function actionGoodsprice(){
      $id = \Yii::$app->request->get('goods_id');
      $url = '';
      $data['goods_id'] = $id;
      $result = $this->curl->setPostParams($data)->post($url);

      return $result;
  }

  public function actionAccount(){
      $id = \Yii::$app->request->get('id');
      $state = \Yii::$app->request->get('state');
      $model = AccountRecord::find()->where(['customer_id'=>$id]);
      if (!empty($state)) {
          $model->andWhere(['state' => $state]);
      }
      $dataProvider = new ActiveDataProvider([
          'query' => $model,
          'pagination' => ['pageSize' => 12,'pageSizeParam'=>false,'pageParam'=>'p'],
          'sort' => [
              'defaultOrder' => [
                  'id' => SORT_DESC,
              ]
          ],

      ]);
      return $this->render('account',['dataProvider'=>$dataProvider]);
  }
  public function actionAccountsee(){
      $this->layout='@app/views/layouts/iframe.php';
      $id = \Yii::$app->request->get('id');
      $model = AccountRecord::findOne($id);
      return $this->render('accountsee',['model'=>$model]);

  }

}
